'use strict';

/**
 * @name VansC2B测试接口 使用Moongo
 * @version 1.0.0
 * @author ljr
 * @Time 2020年12月4日14：10：00
 */
// const TopClient = require('./topClient').TopClient;

// var client = new TopClient({
//   appkey: '28370694',
//   appsecret: '12342f554ecd9851da05743558f0dee8',
//   url: 'http://gw.api.taobao.com/router/rest',
// });

// const orderModel = require('./model/orderModel')
// 添加多条记录    返回值是一个数组，内容为添加的内容
exports.main = async function (context) {
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').insertMany([
    {
      name: 'tom3',
      age: 1
    },
    {
      name: 'jerry',
      age: 2
    }
  ]);
  return result;
}

//删除记录
exports.deleteRecord = async (context) => {
  const cloud = context.cloud;
  cloud.db.collection('todos').deleteMany({
    age: { $gt: 18 }
  }).then((res) => {
    console.log(res)
  })
}

// 查询 年龄小于18的用户   //返回值是一个对象数组 过滤条件未明确
exports.selRecord = async function (context) {
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').find(
    {
      time: { $lt: curentTime() }
    },
    {
      sort: {time: 1}, 
      limit:1
    }
  )
  return result;
}

// 替换 把name为tom3的age修改为18，但只修改一条记录 ， 修改成功返回值为true。
exports.replace = async function (context) {
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').replaceOne(
    {
      name: 'tom3',
    },
    {
      name: 'tom3',
      age: 18
    },
  );
  return result;
}

//更新   返回值为修改的记录条数
exports.update = async function (context) {
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').updateMany({
    _id: '5fc9daa13075d9cd0c951817'
  }, {
    $set: {
      time: curentTime()
    }
  });
  return result;
}

// 获取集合中复合条件的记录数量 统计年龄小于18的用户数量    //返回值为统计总数 5
exports.countUser = async function (context) {
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').count(
    {
      age: { $lt: 18 }
    }
  );
  return result;
}

// 对集合执行聚合查询   返回name=jerry 的俩条记录
exports.aggregateUser = async function (context) {
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').aggregate([
    {
      $match: { name: 'jerry' }
    }
  ]);
  return result;
}

//分组查询
exports.grouping = async (context)=>{
  const cloud = context.cloud;
  const result = await cloud.db.collection('todos').aggregate([
    {$group:{_id:"$name",count:{$sum:1}}},
  ]);
  return result;
}

//存储用户全部的订单信息
//根据订单编号去查询订单信息，定时任务查看是否从预下单变成已下单
//接口需要传递的参数：
//buyer_open_id
//buyer_nick
exports.getUserOrderInfo = async (ctx) => {
  const { cloud } = ctx;
  try {
    let obj = await getPartOrder(ctx);

    if (obj != 'error') {
      let arr = [];
      let obj_02 = {};
      for (let i = 0; i < obj.trades.trade.length; i++) {

        for (let j = 0; j < obj.trades.trade[i].orders.order.length; j++) {
          obj_02 = {
            'open_id': obj.trades.trade[i].buyer_open_uid, //'open_id 用于拉取订单',
            'order_id': obj.trades.trade[i].orders.order[j].oid, //'项目订单id',             
            'order_data': JSON.stringify(obj.trades.trade[i].orders.order[i]), //定制详情
            'state': obj.trades.trade[i].orders.order[j].status, //订单交易状态
            'item_id': obj.trades.trade[i].orders.order[j].num_iid, //商品数字id
            'sku_id':obj.trades.trade[i].orders.order[j].sku_id,  //商品的最小库存单位Sku的id.
            'payment': obj.trades.trade[i].orders.order[j].payment,  //价格
            'create_time':curentTime(),
            "update_time":curentTime(),
          }
          arr.push(obj_02)
        }
      }
      const res = await addOrderInfo(ctx, arr);
      return res;
    }
  } catch (error) {

  }
}

//根据订单编号去查询订单信息，定时任务查看是否从预下单变成已下单
//接口需要传递的参数：
//tid
exports.getUserOrderStatusInfo = async (ctx) => {
  const { cloud } = ctx;
  try {
    let obj = await getOrderStatusByTid(ctx);
    if (obj != 'error') {

      return obj;
    }
  } catch (error) {

  }
}

//根据用户的buyer_open_id||buyer_nick  查询用户的订单列表信息包含交易编号
let getPartOrder = async (ctx) => {
  const { cloud, data: { page_no = 1, page_size = 100, buyer_open_id = 'AAE6rFnxAJuoLN3qJ7Nx_zvh', buyer_nick = 'deamr66' } } = ctx;
  try {
    const result = await cloud.topApi.invoke({
      api: 'taobao.open.trades.sold.get',
      autoSession: true,
      data: {
        'fields': 'tid,type,status,payment,orders,rx_audit_status,buyer_nick',
        //  buyer_open_id,
        page_no,
        page_size,
        buyer_nick,
      }
    });
    return result;
  } catch (err) {
    return "error"
  }
}

//根据交易编号 tid 去 查询订单状态
let getOrderStatusByTid = async (ctx) => {
  const { cloud, data: { tid = "1426625031535095171" } } = ctx;
  try {
    const result = await cloud.topApi.invoke({
      api: 'taobao.open.trade.get',
      autoSession: true,
      data: {
        fields: 'tid,type,status,payment,orders,buyer_nick',
        tid,
      }
    });
    return result;
  } catch (err) {
    return "error"
  }
}


var curentTime = function (time) {
  var d = time ? new Date(time) : new Date();
  var localTime = d.getTime();
  var localOffset = d.getTimezoneOffset() * 60000; //获得当地时间偏移的毫秒数
  var utc = localTime + localOffset + 3600000 * 8;
  var now = new Date(utc);

  var year = now.getFullYear(); //年
  var month = now.getMonth() + 1; //月
  var day = now.getDate(); //日
  var hh = now.getHours(); //时
  var mm = now.getMinutes(); //分
  var ss = now.getSeconds(); //秒

  var clock = year + "-";

  if (month < 10)
    clock += "0";

  clock += month + "-";

  if (day < 10)
    clock += "0";

  clock += day + " ";

  if (hh < 10)
    clock += "0";

  clock += hh + ":";

  if (mm < 10)
    clock += "0";

  clock += mm + ":";

  if (ss < 10)
    clock += "0";

  clock += ss;

  return (clock);
}